package com.yvon.service.demo.algorithm.offer;

import com.yvon.service.demo.algorithm.offer.ext.ListNode;

/**
 * 删除链表的节点
 *
 * 给定单向链表的头指针和一个要删除的节点的值，定义一个函数删除该节点。
 * 返回删除后的链表的头节点。
 * https://doocs.gitee.io/leetcode/#/lcof/%E9%9D%A2%E8%AF%95%E9%A2%9818.%20%E5%88%A0%E9%99%A4%E9%93%BE%E8%A1%A8%E7%9A%84%E8%8A%82%E7%82%B9/README
 */
public class P18 {

    public static void main(String[] args) {
        ListNode<Integer> listNode5 = new ListNode<>(5, null);
        ListNode<Integer> listNode4 = new ListNode<>(4, listNode5);
        ListNode<Integer> listNode3 = new ListNode<>(3, listNode4);
        ListNode<Integer> listNode2 = new ListNode<>(2, listNode3);
        ListNode<Integer> listNode1 = new ListNode<>(1, listNode2);
        ListNode<Integer> head = new ListNode<>(0, listNode1);

        Solution solution = new P18().new Solution();
        ListNode<Integer> integerListNode = solution.deleteNode(head, 4);
        ListNode.printLinkedList(integerListNode);
    }

    class Solution {
        public ListNode<Integer> deleteNode(ListNode<Integer> head, int val) {
            ListNode<Integer> pummy = new ListNode<>(0, head);
            ListNode<Integer> pre = pummy;
            for (ListNode<Integer> p = head; p != null ; p = p.next) {
                if (p.value == val) {
                    pre.next = p.next;
                    break;
                }
                pre.next = p;
            }
            return pummy.next;
        }
    }
}
